package com.gzhryc.net_marketing.cloud.business.services;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.net_marketing.cloud.MarketConstants;
import com.gzhryc.net_marketing.cloud.account.dao.db.CloudPayAccount;
import com.gzhryc.net_marketing.cloud.account.dao.enums.CloudPayAccountEnum;
import com.gzhryc.net_marketing.cloud.account.services.CloudPayAccountService;
import com.gzhryc.net_marketing.cloud.business.dao.db.MarketProjectApp;
import com.gzhryc.net_marketing.cloud.business.dao.enums.MarketProjectAppEnum;
import com.gzhryc.net_marketing.cloud.business.dao.MarketProjectAppDao;
import com.gzhryc.net_marketing.cloud.business.services.dto.MarketProjectAppSearch;
import org.apache.commons.lang3.StringUtils;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class MarketProjectAppService {

    static Logger log = Logger.getLogger(MarketProjectAppService.class);

    public static MarketProjectAppService self() {
        return MultiDBTools.getService(MarketConstants.JDBC_KEY,MarketProjectAppService.class, true);
    }

    public static MarketProjectAppService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, MarketProjectAppService.class, true);
    }

    MarketProjectAppDao dao;

    public MarketProjectAppService(String jdbcKey) {
        dao = new MarketProjectAppDao(jdbcKey);
    }

    public List<MarketProjectApp> findBySearch(MarketProjectAppSearch search, Integer pageNo, Integer pageLimit) {
        Conditions conditions = dao.buildConditions(search);
        if(search.getHasDBConfig() != null){
            if(search.getHasDBConfig()){
            	conditions.and().isNotNull("dbConfig");
            }else{
            	conditions.and().isNull("dbConfig");
            }
        }
        conditions.desc("createDate");
        try {
            return dao.findJoinByCondition(conditions, pageNo, pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public Long countBySearch(MarketProjectAppSearch search) {
        Conditions conditions = dao.buildConditions(search);
        if(search.getHasDBConfig() != null){
            if(search.getHasDBConfig()){
            	conditions.and().isNotNull("dbConfig");
            }else{
            	conditions.and().isNull("dbConfig");
            }
        }
        try {
            return dao.countJoin(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        return 0L;
    }

    public List<MarketProjectApp> findBySearch(MarketProjectAppSearch search) {
        Conditions conditions = dao.buildConditions(search);
        if(search.getHasDBConfig() != null){
            if(search.getHasDBConfig()){
            	conditions.and().isNotNull("dbConfig");
            }else{
            	conditions.and().isNull("dbConfig");
            }
        }
        try {
            return dao.findByCondition(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }
    
    public MarketProjectApp getById(Long id) {
    	try {
			return dao.getById(id);
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
    	return null;
    }

    public MarketProjectApp getByAccountId(Long accountId) {
    	if(accountId != null) {
	        Conditions conditions = new Conditions(MarketProjectApp.class);
	        conditions.and().is("accountId", accountId);
	        try {
	            return dao.get(conditions);
	        } catch (SQLException e) {
	            log.error(e.getMessage(), e);
	        }
    	}
        return null;
    }

    public boolean add(MarketProjectApp app,String phone) throws LogicException {
        app.setCreateDate(new Date());
        
        CloudPayAccount cloudPayAccount = new CloudPayAccount();
        cloudPayAccount.setSecurityPhone(phone);
        cloudPayAccount.setType(CloudPayAccountEnum.Type.MarketApp.index());
        
        JdbcSession.begin();
        try {
        	 //添加云支付账号
            if(CloudPayAccountService.self().add(cloudPayAccount)){
            	app.setAccountId(cloudPayAccount.getId());
            	if(dao.insert(app) > 0){
                    JdbcSession.commit();
                    return true;
                }
            }else{
                throw new LogicException("新增云支付账号失败");
            }
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }finally {
            JdbcSession.end();
        }
        return false;
    }
    
    public boolean toSwitchState(Long id)throws LogicException{
    	MarketProjectApp app = this.getById(id);
    	if(app != null) {
    		if(StringTools.isNotBlank(app.getDbConfig())) {
	    		MarketProjectApp updateEntity = new MarketProjectApp();
	    		updateEntity.setId(id);
	    		if(MarketProjectAppEnum.State.Enable.index().equals(app.getState())) {
	    			updateEntity.setState(MarketProjectAppEnum.State.Wait.index());
	    		}else {
	    			updateEntity.setState(MarketProjectAppEnum.State.Enable.index());
	    		}
	    		
	    		try {
					return dao.updateNotNull(updateEntity) > 0;
				} catch (SQLException e) {
					log.error(e.getMessage(), e);
				}
    		}else {
    			throw new LogicException("未配置数据库");
    		}
    	}
    	return false;
    }

    public boolean updateNotNull(MarketProjectApp app) throws LogicException {
        try {
            return dao.updateNotNull(app) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    public boolean updateDbConfig(Long id, String dbConfig) throws LogicException {
        if (id != null && StringUtils.isNotBlank(dbConfig)) {
            MarketProjectApp app = new MarketProjectApp();
            app.setId(id);
            app.setDbConfig(dbConfig);

            try {
                return dao.updateNotNull(app) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return false;
    }

    public boolean deleteById(Long id) throws LogicException {
        if (id != null) {
        	MarketProjectApp app = getById(id);
        	if(app != null) {
        		//获取云支付账号
                CloudPayAccount cloudPayAccount = CloudPayAccountService.self().getById(app.getAccountId());
                if (cloudPayAccount != null) {
                    if (cloudPayAccount.getMoney() > 0 || cloudPayAccount.getFreezeMoney() > 0) {
                        throw new LogicException("云支付账号存在余额，不允许删除");
                    }
                }
                JdbcSession.begin();
                try {
                    
                    if (dao.deleteById(id) > 0) {
                        //存在则删除云支付账号
                        if (cloudPayAccount != null) {
                            if (CloudPayAccountService.self().faceDeleteById(cloudPayAccount.getId())) {
                                JdbcSession.commit();
                                return true;
                            }
                        } else {
                            JdbcSession.commit();
                            return true;
                        }
                    }
                } catch (SQLException e) {
                    log.error(e.getMessage(), e);
                } finally {
                    JdbcSession.end();
                }
        	}
        }
        return false;
    }
}
